package com.iss.supermarket.UserMangerUI;

import com.iss.supermarket.util.List.ListModelArray;
import com.iss.supermarket.util.MessageWindow.MsgWin;
import com.iss.supermarket.util.entity.SpUser;
import com.iss.supermarket.util.repository.UserDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

public class UserManagerUI extends JFrame{
    private static UserManagerUI userManagerUI;
    private UserManagerList userManagerList;
    private JLabel[] userManagerLabels;
    private JButton jButton1,jButton2,jButton3,jButton4,jButton5,jButton6,jButton7,jButton8;
    private JPanel userManagerPanel,userManagerListPanel;
    private JComboBox<String>[] userManagerComboBoxes;
    private static List<SpUser> userList;

    //连接数据库
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:/spring_ioc.xml");
    UserDao userDao = ctx.getBean("UserDao", UserDao.class);

    public UserManagerUI(){
        InitAssembly();
        InitUI();
    }

    private void InitUI(){
        Container container = getContentPane();
        Box verticalBox = Box.createVerticalBox();

        JPanel jPanel1 = new JPanel();
        jPanel1.add(userManagerLabels[0]);
        jPanel1.add(userManagerComboBoxes[0]);
        verticalBox.add(jPanel1);

        JPanel jPanel2 = new JPanel();
        jPanel2.add(userManagerLabels[1]);
        jPanel2.add(userManagerComboBoxes[1]);
        verticalBox.add(jPanel2);

        JPanel jPanel3 = new JPanel();
        jPanel3.add(userManagerLabels[2]);
        jPanel3.add(userManagerComboBoxes[2]);
        verticalBox.add(jPanel3);

        JPanel jPanel4 = new JPanel();
        jPanel4.add(userManagerLabels[3]);
        jPanel4.add(userManagerComboBoxes[3]);
        verticalBox.add(jPanel4);

        JPanel jPanel5 = new JPanel();
        jPanel5.add(userManagerLabels[4]);
        jPanel5.add(userManagerComboBoxes[4]);
        verticalBox.add(jPanel5);

        JPanel jPanel6 = new JPanel();
        jPanel6.add(jButton5);
        jPanel6.add(jButton1);
        verticalBox.add(jPanel6);

        verticalBox.add(userManagerListPanel);

        JPanel jPanel7 = new JPanel();
        jPanel7.add(jButton4);
        jPanel7.add(jButton3);
        jPanel7.add(jButton2);
        jPanel7.add(jButton6);
        jPanel7.add(jButton7);
        jPanel7.add(jButton8);
        verticalBox.add(jPanel7);

        userManagerPanel.add(verticalBox);
        userManagerPanel.setPreferredSize(new Dimension(1600,800));
//        container.add(userManagerPanel);
//        setSize(1600,800);
//        setVisible(true);
    }

    private void InitAssembly(){
        userManagerPanel = new JPanel();
        userManagerListPanel = new JPanel();

        userList = new ArrayList<SpUser>();
        userList = userDao.queryUserList();

        userManagerLabels = new JLabel[5];
        userManagerLabels[0] = new JLabel("根据用户UUID查询：");
        userManagerLabels[1] = new JLabel("根据用户名查询：");
        userManagerLabels[2] = new JLabel("根据用户手机号码查询：");
        userManagerLabels[3] = new JLabel("根据用户邮箱查询：");
        userManagerLabels[4] = new JLabel("根据用户角色查询：");

        for(int i=0;i<userManagerLabels.length;++i){
            userManagerLabels[i].setPreferredSize(new Dimension(180,25));
            userManagerLabels[i].setHorizontalAlignment(SwingConstants.LEFT);
            userManagerLabels[i].setFont(new Font("黑体",Font.PLAIN,15));
        }

        userManagerComboBoxes = new JComboBox[5];
        for(int i=0;i<userManagerComboBoxes.length;++i){
            userManagerComboBoxes[i] = new JComboBox<String>();
            userManagerComboBoxes[i].setEditable(true);
            userManagerComboBoxes[i].setPreferredSize(new Dimension(300,25));
            userManagerComboBoxes[i].addItem("无");
            userManagerComboBoxes[i].setSelectedItem("");
            userManagerComboBoxes[i].addItemListener(new ItemAction());
            userManagerComboBoxes[i].setFont(new Font("黑体",Font.PLAIN,15));
        }

        for(int i=0;i<userList.size();++i){
            userManagerComboBoxes[0].addItem(userList.get(i).getUserUuid());
        }

        for(int i=0;i<userList.size();++i){
            userManagerComboBoxes[1].addItem(userList.get(i).getUserName());
        }

        for(int i=0;i<userList.size();++i){
            userManagerComboBoxes[2].addItem(userList.get(i).getMobile());
        }

        for(int i=0;i<userList.size();++i){
            userManagerComboBoxes[3].addItem(userList.get(i).getEmail());
        }

        userManagerComboBoxes[4].addItem("管理员");
        userManagerComboBoxes[4].addItem("收银员");
        userManagerComboBoxes[4].addItem("仓库管理员");
        userManagerComboBoxes[4].addItem("售后管理员");

        jButton1 = new JButton("查询");
        jButton1.addActionListener(new ButtonAction());
        jButton1.setFont(new Font("黑体",Font.PLAIN,14));

        jButton2 = new JButton("锁定用户");
        jButton2.addActionListener(new ButtonAction());
        jButton2.setFont(new Font("黑体",Font.PLAIN,14));

        jButton3 = new JButton("增加用户");
        jButton3.addActionListener(new ButtonAction());
        jButton3.setFont(new Font("黑体",Font.PLAIN,14));

        jButton4 = new JButton("编辑用户角色与权限");
        jButton4.addActionListener(new ButtonAction());
        jButton4.setFont(new Font("黑体",Font.PLAIN,14));

        jButton5 = new JButton("查询全部");
        jButton5.addActionListener(new ButtonAction());
        jButton5.setFont(new Font("黑体",Font.PLAIN,14));

        jButton6 = new JButton("重置用户密码");
        jButton6.addActionListener(new ButtonAction());
        jButton6.setFont(new Font("黑体",Font.PLAIN,14));

        jButton7 = new JButton("解锁用户");
        jButton7.addActionListener(new ButtonAction());
        jButton7.setFont(new Font("黑体",Font.PLAIN,14));

        jButton8 = new JButton("保存");
        jButton8.addActionListener(new ButtonAction());
        jButton8.setFont(new Font("黑体",Font.PLAIN,14));

        userManagerList = UserManagerList.getuserManagerList();
        userManagerListPanel = userManagerList.getUserManagerListPanel();
    }

    private class ItemAction implements ItemListener{
        @Override
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange() == ItemEvent.SELECTED){
                if("无".equals(e.getItem())){
                    //获得事件所作用的对象
                    JComboBox<String> tmp = (JComboBox<String>) e.getSource();
                    tmp.setSelectedItem("");
                }

            }
        }
    }

    private class ButtonAction implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e){
            JList<SpUser> jList =  userManagerList.getjList();
            //获得jlist中被选中的项，支持多选
            List<SpUser> spUsers = jList.getSelectedValuesList();

            if("查询".equals(e.getActionCommand())) {
                boolean flushFlag = true;
                userManagerList.Clear();
                //依靠单个查询条件查询出来的呃结果
                SpUser[] spUsersArr = new SpUser[4];
                //依靠用户角色查询出来的结果
                List<SpUser> spUserList = new ArrayList<SpUser>();

                //当查询条件不空时执行查询
                if (userManagerComboBoxes[0].getSelectedItem() != null && !"".equals(String.valueOf(userManagerComboBoxes[0].getSelectedItem()))) {
                    spUsersArr[0] = userDao.queryUserInfoByUUID(userManagerComboBoxes[0].getSelectedItem().toString());
                }
                if (userManagerComboBoxes[1].getSelectedItem() != null && !"".equals(userManagerComboBoxes[1].getSelectedItem())) {
                    spUsersArr[1] = userDao.queryUserInfoByName(userManagerComboBoxes[1].getSelectedItem().toString());
                }
                if (userManagerComboBoxes[2].getSelectedItem() != null && !"".equals(userManagerComboBoxes[2].getSelectedItem())) {
                    spUsersArr[2] = userDao.queryUserInfoByMobile(userManagerComboBoxes[2].getSelectedItem().toString());
                }
                if (userManagerComboBoxes[3].getSelectedItem() != null && !"".equals(userManagerComboBoxes[3].getSelectedItem())) {
                    spUsersArr[3] = userDao.queryUserInfoByEmail(String.valueOf(userManagerComboBoxes[3].getSelectedItem()));
                }
                if (userManagerComboBoxes[4].getSelectedItem() != null && !"".equals(userManagerComboBoxes[4].getSelectedItem())) {
                    spUserList = userDao.queryUserListByRole(String.valueOf(userManagerComboBoxes[4].getSelectedItem()));
                }

                //排除存在多条指向不同的查询结果的查询条件在查询时造成的干扰
                //如uuid和手机号码指向的是不同的用户时，不进行查询
                //只要是存在多个查询条件，且条件只要有一组指向不同查询结果就返回假
                for (int i = 0; i < 4; ++i) {
                    if (spUsersArr[i] == null) {
                        i++;
                    } else {
                        for (int j = i + 1; j < 4; ++j) {
                            if (spUsersArr[j] == null) {
                                j++;
                            }else{
                                if (!(spUsersArr[i].getUserUuid().equals(spUsersArr[j].getUserUuid()))) {
                                    flushFlag = false;
                                }
                            }
                            if(!flushFlag){
                                break;
                            }
                        }
                        if(!flushFlag){
                            break;
                        }
                        if(spUserList.size() > 0){
                            flushFlag = isContain(spUserList, spUsersArr[i]);
                        }
                    }
                }

                if(flushFlag){
                    //当flushFlag为真时刷新jlist，优先刷新指向单个用户的查询条件
                    if(spUsersArr[0] != null || spUsersArr[1] != null || spUsersArr[2] != null || spUsersArr[3] != null){
                        for(int i = 0; i < 4; ++i){
                            if (spUsersArr[i] != null){
                                userManagerList.flushList(spUsersArr[i]);
                                break;
                            }
                        }
                    }else{
                        for(int i = 0; i < spUserList.size(); ++i){
                            userManagerList.flushList(spUserList.get(i));
                        }
                    }
                }else{
                    MsgWin msgWin = new MsgWin("查询失败");
                }
            }
            else if("查询全部".equals(e.getActionCommand())){
                for(int i=0;i<userList.size();++i){
                        userManagerList.flushList(userList.get(i));
                }
            }
            else if("编辑用户角色与权限".equals(e.getActionCommand())){
                RolePanel rolePanel = RolePanel.getRolePanel();

            }else if("重置用户密码".equals(e.getActionCommand())){
                for(int i=0;i<spUsers.size();++i){
                    spUsers.get(i).setPassword("123456");
                }
            }else if("锁定用户".equals(e.getActionCommand())){
                for(int i=0;i<spUsers.size();++i){
                    //删除标识，1做删除，0做未删除
                    spUsers.get(i).setDelFlag(1);
                }

            }else if("增加用户".equals(e.getActionCommand())){
                NewSpUserPanel newSpUserPanel = NewSpUserPanel.getNewSpUserPanel();

            }else if("解锁用户".equals(e.getActionCommand())){
                for(int i=0;i<spUsers.size();++i){
                    for(int j=0;j<userList.size();++j){
                        if(userList.get(j).getUserUuid().equals(spUsers.get(i).getUserUuid())){
                            userList.get(j).setDelFlag(0);
                        }
                    }
                    spUsers.get(i).setDelFlag(0);
                }
                for(int i=0;i<userList.size();++i){
                    userManagerList.flushList(userList.get(i));
                }
            }else if("保存".equals(e.getActionCommand())){
                //用update更新sp_user
                ListModelArray<SpUser> listModelArray = (ListModelArray<SpUser>) jList.getModel();
                for(int i=0;i<listModelArray.getSize();++i){
                    userDao.updateUserInfo(listModelArray.getList().get(i).getUserName(),
                            listModelArray.getList().get(i).getPassword(),
                            listModelArray.getList().get(i).getMobile(),
                            listModelArray.getList().get(i).getEmail(),
                            listModelArray.getList().get(i).getNiceName(),
                            listModelArray.getList().get(i).getUserUuid(),
                            listModelArray.getList().get(i).getRemark(),
                            listModelArray.getList().get(i).getModtime(),
                            listModelArray.getList().get(i).getDelFlag());
                }
                //更新成功返回更新信息
                MsgWin msgWin = new MsgWin("修改成功");
            }
        }

        boolean isContain(List<SpUser> list,SpUser spUser){
            //检测
//            System.out.println("\t\t9");
            for(int i=0;i<list.size();++i){
                System.out.println(list.get(i).getUserUuid());
                if(list.get(i).getUserUuid().equals(spUser.getUserUuid())){
                    return true;
                }
            }
            return false;
        }
    }

    public static synchronized UserManagerUI getUserManagerUI(){
        if(userManagerUI == null){
            userManagerUI = new UserManagerUI();
        }
        return userManagerUI;
    }

    public JPanel getUserManagerPanel(){
        return userManagerPanel;
    }
}